import React, { useState, useMemo } from "react";

/*
  ! useCallback和useMemo的区别
    useCallback缓存的是函数本身
    useMemo缓存的是函数的返回值

    useCallback是可以转成useMemo的，只要return一个函数
    useMemo是转不了useCallback的
*/

const App = () => {
  const [count, setCount] = useState(1);
  const [num, setNum] = useState(10);
  const [list] = useState([1, 2, 3, 4, 5, 6, 7]);
  const [list2] = useState([
    {
      title: "苹果",
      n: 10,
    },
    {
      title: "香蕉",
      n: 15,
    },
    {
      title: "西瓜",
      n: 22,
    },
  ]);

  //! useMemo的用法和useCallback完全相同
  //! useMemo就是相当于vue的计算属性
  const total = useMemo(() => {
    console.log("total");
    let sum = 0;
    for (let i = 0; i < count * 100; i++) {
      sum += i;
    }
    return sum;
  }, [count]);

  const doubleNum = useMemo(() => {
    return num * 2;
  }, [num]);

  const oddList = useMemo(() => {
    return list.filter((item) => item % 2);
  }, [list]);

  const total2 = useMemo(() => {
    return list2.reduce((sum, item) => {
      return (sum += item.n);
    }, 0);
  }, [list2]);

  return (
    <>
      <h2>useMemo</h2>
      <div>count: {count}</div>
      <div>total: {total}</div>
      <button onClick={() => setCount((v) => v + 1)}>count++</button>

      <hr />
      <div>num: {num}</div>
      <div>doubleNum: {doubleNum}</div>
      <button onClick={() => setNum((v) => v + 1)}>num++</button>

      <hr />
      <ul>
        {oddList.map((item, index) => (
          <li key={index}>{item}</li>
        ))}
      </ul>

      <hr />
      <div>总数是: {total2}</div>
    </>
  );
};

export default App;
